package cloud.maque.common.captcha.service.impl;

import cloud.maque.common.captcha.conf.CaptchaProperties;
import cloud.maque.common.captcha.dto.CaptchaDto;
import cloud.maque.common.captcha.service.CaptchaService;
import cn.hutool.core.util.RandomUtil;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.ServletOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;


@Service
public class CaptchaServiceImpl implements CaptchaService {


    @Autowired
    CaptchaProperties captchaProperties;

    @Override
    public CaptchaDto getCaptcha() {
        CaptchaDto captchaDto = new CaptchaDto();
        Captcha captcha = null;

        switch (captchaProperties.getType()) {
            case PNG:
                captcha = getNormalCaptcha();
                break;
            case GIF:
                captcha = getGifCaptcha();
                break;
            case CHINESE:
                captcha = getChineseCaptcha();
                break;
            case ARITHMETIC:
                captcha = getArithmeticCaptcha();
                break;
        }
        captchaDto.setBase64(captcha.toBase64());
        captchaDto.setCode(captcha.text());
        captchaDto.setId(RandomUtil.randomString(10));
        return captchaDto;
    }

    private Captcha getNormalCaptcha() {

        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight(), captchaProperties.getLength());
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, captchaProperties.getFontSize()));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(captchaProperties.getPngType());

        return specCaptcha;
    }

    private Captcha getGifCaptcha() {
        // gif类型
        GifCaptcha captcha = new GifCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        return captcha;
    }

    private Captcha getChineseCaptcha() {
        // 中文类型
        ChineseCaptcha captcha = new ChineseCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        return captcha;
    }

    private Captcha getArithmeticCaptcha() {
        // 算术类型
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        captcha.setLen(3);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.text();  // 获取运算的结果：5
        return captcha;
    }
}
